var DEBUG = false
var PORT = 3100
var INIT_MESSAGES = 8

var http = require('http')

var server = http.createServer()
server.listen(PORT)

var io = require('socket.io').listen(server)
io.set ('transports', ['xhr-polling', 'jsonp-polling'])

var messages = new Array()

// INIT_MESSAGES stores the number of prev messages in the buffer 
// and decides how many messages will be passed to the user. 
Array.prototype.inject = function(element) {

    if (this.length >= INIT_MESSAGES) {
        this.shift()
    }
    this.push(element)
}

// var main = io.of('/file')
//                 .on('connection', function(socket){
//                     socket.on('requestNs', function(data, join_cb){
//                         join_cb({'namespace': data['docID']});
//                     });
//     if (DEBUG)
//         console.log("New Connection: ", socket.id)

//     socket.emit("init", JSON.stringify(messages))

//     socket.on('msg', function(msg) {

//         if (DEBUG)
//             console.log("Message: " + msg)

//         var message = JSON.parse(msg)
//         messages.inject(message)

//         socket.broadcast.emit('msg', msg)
//     })

//     socket.on('disconnect', function() {

//         if (DEBUG)
//             console.log("Disconnected: ", socket.id)
//     })
//                 });

io.sockets.on('connection', function(client) {

    if (DEBUG)
        console.log("New Connection: ", client.id)
    // Send 'init' signal to connected client.
    client.emit("init", JSON.stringify(messages))

    client.on('msg', function(msg) {

        if (DEBUG)
            console.log("Message: " + msg)

        var message = JSON.parse(msg)
        messages.inject(message)
        // Send recieved message to all clients. 
        client.broadcast.emit('msg', msg)
    })

    client.on('disconnect', function() {

        if (DEBUG)
            console.log("Disconnected: ", client.id)
    })
})
